<?php

namespace fast;


    class Wxsdk
    {
        private $appId;
        private $appSecret;
        
        public function __construct($appId='wx63c391768f362ca80', $appSecret='512ec5eb6117b86bcaccf3f10b45edc2') {
            $this->appId = $appId;
            $this->appSecret = $appSecret;
        }


	    // public function islogin(){
	    //     //验证是否登录过，如果没有登录就跳转
	    //      if(empty(session('user'))){
	    //             // $this->getUserOpenId();
	    //             return false;
	    //         // $this->redirect('/index/index/me');
	    //             // exit();
	    //         }else{
	    //             // echo " ";
	    //             return true;
	    //             // dump(session('openid'));
	    //         }
	    // }

     //    public function login(){
     //        // $user ='1111';
	    //     $user = $this->getUserOpenId();
	    //     return $user;
	    // }

/*
	    public function getBaseInfo(){
	        //1.获取到code        
	       
	       
	        // $redirect_uri=urlencode($this->domain()."/index/index/");//跳转 可以自己改参数 QQ496631085
            $tiaozhuan = $this->domain()."/index/index/login";
             if(!empty($_SERVER['HTTP_REFERER'])){
                $tiaozhuan = $_SERVER['HTTP_REFERER'];
             }
             // else{
             //    $this->redirect($this->_domain.'/index/index/index');
             // }
             
            $redirect_uri=urlencode($tiaozhuan);

	        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appId."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=xiaohe#wechat_redirect";

            echo '<script>;location.href="'.$url.'";</script>;';
            exit();
	    }




	   

	     //查询这个用户的信息
	    public function openid_nickname($openid){
	       $nickname = Db::name('wxuser')->where('openid',$openid)->find();
	       return $nickname['nickname'];
	    }

	    //获取用户的openid等信息
	    public function getUserOpenId(){
	        if(!empty($_SERVER['HTTP_REFERER']))
	        file_put_contents('tiaozhuan.txt', $_SERVER['HTTP_REFERER'].'\r\n',FILE_APPEND);
	        // exit($_GET);
	        //2.获取到网页授权的access_token        
	        
	        
	        // if(empty($this->request->get('code'))){
	    	if(empty($_GET['code'])){
	            $this->getBaseInfo();
	            // exit();
	        }
	        // dump($this->request->get());
	        $code = $_GET['code'];//?????????????????
	        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appId."&secret=".$this->appSecret."&code=".$code."&grant_type=authorization_code ";
	        //3.拉取用户的openid
	        $res = file_get_contents($url);

	        $data = json_decode($res,true);
	        if(!empty($data['access_token']) && !empty($data['openid'])){
	            $this->access_token=$data['access_token'];
	            $this->refresh_token=$data['refresh_token'];
	            
	            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN"; 
	            $userInfo = file_get_contents($url);
	            $user_res = json_decode($userInfo,true);
	            // echo $userInfo;
                session('user',$user_res);
	            return $user_res;


	        }else{
                dump($data);
	        	return 0;
	        	// $this->getUserOpenId();
	        	exit();
	        }
	    }
        */

        // public function get_user_all(){
        //     if (!isset($_GET['code'])){//没有code，去微信接口获取code码
        //         $callback = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];//微信服务器回调url，这里是本页url
        //         $this->get_code($callback);
        //     } else {//获取code后跳转回来到这里了
        //         $code = $_GET['code'];
        //         $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
        //         $data_all = $this->get_user_info($data['access_token'],$data['openid']);//获取微信用户信息
        //         return $data_all;
        //     }
        // }
        // /**
        //  * 2、用户授权并获取code
        //  * @param string $callback 微信服务器回调链接url
        //  */
        // private function get_code($callback){
        //     $appid = $this->appid;
        //     $scope = 'snsapi_userinfo';
        //     $state = md5(uniqid(rand(), TRUE));//唯一ID标识符绝对不会重复
        //     $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) .  '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
        //     header("Location:$url");
        // }
        // /**
        //  * 3、使用code换取access_token
        //  * @param string 用于换取access_token的code，微信提供
        //  * @return array access_token和用户openid数组
        //  */
        // private function get_access_token($code){
        //     $access_token_file = './access_token.txt';
        //     $get_data_status = false;
        //     $data = file_get_contents($access_token_file);
        //     if($data){
        //         $data = json_decode($data,true);
        //         $expire_time = isset($data['expire_time'])?$data['expire_time']:'0';
        //         if(time() > ($expire_time - 600)){
        //             $get_data_status = true;
        //         }
        //     }else{
        //         $get_data_status = true;
        //     }
        //     if($get_data_status == true){
        //         $appid = $this->appid;
        //         $appsecret = $this->appsecret;
        //         $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        //         $user = json_decode(file_get_contents($url));
        //         if (isset($user->errcode)) {
        //             echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
        //         }
        //         $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        //         $data['expire_time'] = time()+$data['expires_in'];
        //         file_put_contents($access_token_file,json_encode($data));
        //     }

        //     return $data;
        // }
        // /**
        //  * 4、使用access_token获取用户信息
        //  * @param string access_token
        //  * @param string 用户的openid
        //  * @return array 用户信息数组
        //  */
        // private function get_user_info($access_token,$openid){
        //     $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        //     $user = json_decode(file_get_contents($url));
        //     if (isset($user->errcode)) {
        //         echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
        //     }
        //     $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        //     return $data;
        // }

        // //对外开放，获取access_token
        // public function get_access_token_open(){
        //     if (!isset($_GET['code'])){//没有code，去微信接口获取code码
        //         $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://": "http://";
        //         //$callback = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];//微信服务器回调url，这里是本页url
        //         $callback = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];//微信服务器回调url，这里是本页url
        //         $this->get_code($callback);
        //     } else {//获取code后跳转回来到这里了
        //         $code = $_GET['code'];
        //         $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
        //         return $data;
        //     }
        // }



         /**
         * 判断是否为https
         * @return bool 是https返回true;否则返回false
         */
        public function domain() {
            if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
                return 'https://'.$_SERVER['HTTP_HOST'];
            } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
                return 'https://'.$_SERVER['HTTP_HOST'];
            } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
                return 'https://'.$_SERVER['HTTP_HOST'];
            }else{
                return 'http://'.$_SERVER['HTTP_HOST'];
            }
        }

        
        public function getSignPackage() {
            $jsapiTicket = $this->getJsApiTicket();
            
            // 注意 URL 一定要动态获取，不能 hardcode.
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            
            $timestamp = time();
            $nonceStr = $this->createNonceStr();
            
            // 这里参数的顺序要按照 key 值 ASCII 码升序排序
            $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
            
            $signature = sha1($string);
            
            $signPackage = array(
                "appId"     => $this->appId,
                "nonceStr"  => $nonceStr,
                "timestamp" => $timestamp,
                "url"       => $url,
                "signature" => $signature,
                "rawString" => $string
            );
            return $signPackage;
        }
        
        private function createNonceStr($length = 16) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            $str = "";
            for ($i = 0; $i < $length; $i++) {
                $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            }
            return $str;
        }
        
        private function getJsApiTicket() {
            // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
            if(file_get_contents("jsapi_ticket.json")){
                $data = json_decode(file_get_contents("jsapi_ticket.json"));
            }else{
                $data = null;
            }
            
            if ($data->expire_time < time()) {
                $accessToken = $this->getAccessToken();
                // 如果是企业号用以下 URL 获取 ticket
                // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
                $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
                $res = json_decode($this->httpGet($url));
                $ticket = $res->ticket;
                if ($ticket) {
                    $data->expire_time = time() + 7000;
                    $data->jsapi_ticket = $ticket;
                    $fp = fopen("jsapi_ticket.json", "w");
                    fwrite($fp, json_encode($data));
                    fclose($fp);
                }
            } else {
                $ticket = $data->jsapi_ticket;
            }
            
            return $ticket;
        }
        
        public function getAccessToken() {
            // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
                // file_put_contents("access_token.json",'{"expire_time":1583827757,"access_token":"31_Un3zSNcjKoguvonQp09KBg2kSH11qbPIn_7NxAp7Ya23q1ZhlsdTFyKRSy7HI0E81iXm3PMMvItbruoYuD8-BV8cBvNt13hfp-HrBmcqDCr7TLJW0w8uR8Gs-38YO-NjpF3JI0k2kRy70YEUXGOfACAAJR"}');
            $data = json_decode(file_get_contents("access_token.json"));
            if ($data->expire_time < time()) {
                // 如果是企业号用以下URL获取access_token
                // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
                $res = json_decode($this->httpGet($url));
                /**
                加入错误代码提示
                **/
                if(isset($res->errcode)){
                  halt('error_code:'.$res->errcode.$res->errmsg);
                }

                $access_token = $res->access_token;
                if ($access_token) {
                    $data->expire_time = time() + 7000;
                    $data->access_token = $access_token;
                    $fp = fopen("access_token.json", "w");
                    fwrite($fp, json_encode($data));
                    fclose($fp);
                }
            } else {
                $access_token = $data->access_token;
            }
            return $access_token;
        }
        
        private function httpGet($url) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 500);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_URL, $url);
            
            $res = curl_exec($curl);
            curl_close($curl);
            
            return $res;
        }
    }